package com.zqxq.lottery.api.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.internal.util.StringUtils;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.request.AlipayUserInfoShareRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import com.zqxq.common.utils.DateUtils;
import com.zqxq.lottery.api.config.AlipayConfig;
import com.zqxq.lottery.api.config.YmlConfig;
import com.zqxq.lottery.api.service.IAlipayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;

/**
 * @Description ：
 * @Author ： 解风
 * @Date ： 2018/03/22 17:28
 */
@Service
@Slf4j
public class AlipayServiceImpl implements IAlipayService{

//    private static final String serverUrl = "https://openapi.alipay.com/gateway.do";
//    private static final String appId = "2018032102418619";//应用ID
//    private static final String pId = "2088521333892422";//用户账号
//    private static final String privateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCNvMugrQY5gnbpf0XGmTcb8/Rm+pSFUzXH0P0S4gT5mNV17dO8zd5hwkf5sIzfhSODzYs/wGPAAAKKL5zxT46X0N/wcei8fhS9wcDH+2DtvudE5gKhM/Vs3AVG0N+xHmoiD7Hlk/nyw1p2qm3pQXR7XwPo2h5KYTF3vS4QQBAFucUDGXU5LkfYT4HA6v5d3QhyXFcL702r59U52CqBV0WIEjEmEL9kUOqDkgLl6PZQjsa7XT/T15ATqF8rLCYi8kCeL+VUNX0opLj9GLTg1Z/VKpJucbsR4KNAp/pqTu2AVR/qavu2tGVX5z3uXsKouMAuSP1208Lhy9qfcrJsVSA1AgMBAAECggEALUxGQ86o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C2AgGH4NybZMACTnLRa7AxQHZxU12J8mavAoPrKqHRXzS4Njh17Bz7uZTsF1/fBwupncHaCvKUThVnDBPBNJBmqZXbGqWSpteYMPXk6ya5yHNLW8pi3h9AjMRawiiULmliI2jXJImTc+wFAbQW";
//    private static final String publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmVTTES+gHfxx64AkhvBvgZoCPojNnc7wRNC7W3v7phO0svyNPfnXSbpSHG0OiNystPo8qIya5nTl+dWvV04tVQ5hwv3nQMbO1V05qUKKEijgIhZDYaPtgZOtCNZKOUeQRhDHsnyEVuht52Ss+TPBPL9DJ37LyyRQoj/6T9eB97RDyC3k3ptUiQ8wrP9nF+og/LRqH032gTgGwJ8mWEqb6h4wHIJfgEljc5yynzwrxVL7dkyd2alnhCyXrS8yOmwDEV4MsYlgVJUXWNGckKYfXg0hlsmDOqf30PqGOHaJyIBbJ1vt5Ozv4J6oeTQUlaB5A4BX5AF8lazNkIbbbcu+WwIDAQAB";
//    private static final String charset = "utf-8";
//    private static final String notityUrl = "http://218.70.11.118:1034/notify/alipayNotity";//本地测试环境
//    private static final String returnUrl = "https://qsl.qsljrfw.com/QianShiLangWeiXin/help/payBack.html";

    @Autowired
    private YmlConfig ymlConfig;

    @Autowired
    private AlipayConfig alipayConfig;

    @Override
    public String appAuthParams() {
        String authParams = null;
        Map<String ,String> params = new HashMap<String, String>();
        params.put("apiname", "com.alipay.account.auth");
        params.put("method", "alipay.open.auth.sdk.code.get");
        params.put("app_id", alipayConfig.getAppId());
        params.put("app_name", "mc");
        params.put("biz_type", "openservice");
        params.put("pid", alipayConfig.getPId());//用户账号
        params.put("product_id", "APP_FAST_LOGIN");
        params.put("scope", "kuaijie");
        params.put("target_id", ymlConfig.getPkId().toString());//唯一ID
        params.put("auth_type", "AUTHACCOUNT");
        params.put("sign_type", "RSA2");
        String sign = null;
        try{
            sign = AlipaySignature.rsaSign(params, alipayConfig.getPrivateKey(), alipayConfig.getCharset());
            log.info("sign-------------->:" + sign);
            sign = URLEncoder.encode(sign, alipayConfig.getCharset());
            log.info("URLEncoder sign-------------->:" + sign);
            params.put("sign", sign);
            authParams = AlipaySignature.getSignContent(params);
        } catch (Exception e) {
            log.error("alipay appAuth is error",e);
        }
        return authParams;
    }

    @Override
    public String getAccessToken(String authCode) {
        String result = null;
        AlipayClient alipayClient = getAlipayClient();
        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
        request.setCode(authCode);
        request.setGrantType("authorization_code");
        try {
            AlipaySystemOauthTokenResponse oauthTokenResponse = alipayClient.execute(request);
            result = oauthTokenResponse.getAccessToken();
            log.info(result);
        } catch (AlipayApiException e) {
            //处理异常
            log.error("alipay getAccessToken is error",e);
        }
        return result;
    }

    @Override
    public String getUser(String accessToken) {
        String result = null;
        AlipayClient alipayClient = getAlipayClient();
        AlipayUserInfoShareRequest request = new AlipayUserInfoShareRequest();
        try {
            AlipayUserInfoShareResponse userinfoShareResponse = alipayClient.execute(request, accessToken);
            result = userinfoShareResponse.getBody();
            log.info(result);
        } catch (AlipayApiException e) {
            //处理异常
            log.error("alipay getUser is error",e);
        }
        return result;
    }

    @Override
    public String rechargeParams(Long userId, BigDecimal money) {
        return payParams(userId, ymlConfig.getPkId(),null,null, 0, money, "充值");
//        return getWebPay(userId, ymlConfig.getPkId(), 0, money);
    }

    @Override
    public String consumeParams(Long userId, Long orderId,Long couponId,BigDecimal balance, BigDecimal money) {
        return payParams(userId, orderId,couponId,balance, 1, money, "消费");
    }

    private AlipayClient getAlipayClient(){
        return new DefaultAlipayClient(alipayConfig.getServerUrl(), alipayConfig.getAppId(), alipayConfig.getPrivateKey(), "json", alipayConfig.getCharset(), alipayConfig.getPublicKey(), "RSA2");
    }

    private String payParams(Long userId, Long orderId,Long couponId,BigDecimal balance, Integer type, BigDecimal money, String payNotes){
        String result = null;
        Map<String ,String> params = new HashMap<String, String>();
        params.put("app_id", alipayConfig.getAppId());
        params.put("method", "alipay.trade.app.pay");
        params.put("format", "JSON");
        params.put("charset", alipayConfig.getCharset());
        params.put("sign_type", "RSA2");
        params.put("timestamp", DateUtils.getCurrentDateTimeStr());
        params.put("version", "1.0");
        params.put("notify_url", alipayConfig.getNotityUrl());
        String sign;
        try{
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("subject", payNotes);
            jsonObject.put("out_trade_no", orderId);
            jsonObject.put("timeout_express", "1c");
            jsonObject.put("total_amount", money.setScale(2,4).toString());
//            jsonObject.put("total_amount", "1");
            jsonObject.put("product_code", "QUICK_MSECURITY_PAY");
            String passback_params = URLEncoder.encode( type + "," + userId + "," + couponId + "," + balance, alipayConfig.getCharset());
            jsonObject.put("passback_params", passback_params);
            jsonObject.put("disable_pay_channels","credit_group");
            params.put("biz_content", jsonObject.toJSONString());//业务参数
            String signContent = AlipaySignature.getSignContent(params);
            log.info("sign-params:" + signContent);
            sign = AlipaySignature.rsaSign(signContent, alipayConfig.getPrivateKey(), alipayConfig.getCharset(), "RSA2");
            log.info("sign-------------->:" + sign);
            params.put("sign", sign);
            result = getSignContent(params);
            log.info("result-------------->:" + result);
        } catch (Exception e) {
            log.error("alipay payParams is error",e);
        }
        return result;
    }

    public String getSignContent(Map<String, String> sortedParams) {
        StringBuffer content = new StringBuffer();
        List<String> keys = new ArrayList(sortedParams.keySet());
        Collections.sort(keys);
        int index = 0;

        for(int i = 0; i < keys.size(); ++i) {
            String key = keys.get(i);
            String value = sortedParams.get(key);
            if (StringUtils.areNotEmpty(new String[]{key, value})) {
                try {
                    value = URLEncoder.encode(value, alipayConfig.getCharset());
                }catch (Exception e) {
                    log.error("alipay getSignContent is error",e);
                }
                content.append((index == 0 ? "" : "&") + key + "=" + value);
                ++index;
            }
        }

        return content.toString();
    }

    /**
     * 网页支付
     * @param userId
     * @param orderId
     * @param type
     * @param money
     * @return
     */
    public String getWebPay(Long userId, Long orderId, Integer type, BigDecimal money){
        String form="";
        try {
            AlipayClient alipayClient = getAlipayClient();
            AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();//创建API对应的request
    //        alipayRequest.setReturnUrl(returnUrl); //支付宝业务处理成功后返回的成功页面
            alipayRequest.setNotifyUrl(alipayConfig.getNotityUrl());//在公共参数中设置回跳和通知地址 enable_pay_channels
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("subject", "充值");
            jsonObject.put("out_trade_no", orderId);
            jsonObject.put("timeout_express", "1c");
            jsonObject.put("total_amount", money.setScale(2,4).toString());
            jsonObject.put("product_code", "QUICK_MSECURITY_PAY");
            String passback_params = URLEncoder.encode( type + "," + userId, alipayConfig.getCharset());
            jsonObject.put("passback_params", passback_params);

            alipayRequest.setBizContent(jsonObject.toJSONString());//填充业务参数


            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
            log.info("生成的form表单：form",form);
        } catch (Exception e) {
            log.error("alipay getWebPay is error",e);
        }
        return form;
    }
}
